import os
import base64

from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from .models import OAuthQQUser
from .utils import OAuthQQ
from users.models import User
from meiduo_mall.utils.DBHelper import create_redis_conn


class QQUserSerializer(serializers.ModelSerializer):
    mobile = serializers.RegexField(label='手机号码', regex=r'^1[3-9]\d{9}$', write_only=True)
    sms_code = serializers.CharField(label='短信验证码', write_only=True)
    access_token = serializers.CharField(label='openid', write_only=True)
    token = serializers.CharField(label='token', read_only=True)
    class Meta:
        model = User
        fields = ('id', 'username', 'password', 'mobile', 'sms_code', 'access_token', 'token')
        extra_kwargs = {
            'username': {
                'read_only': True
            },
            'password': {
                'write_only': True,
                'min_length': 8,
                'max_length': 20,
                'error_messages': {
                    'min_length': '仅允许8-20个字符的密码',
                    'max_length': '仅允许8-20个字符的密码'
                }
            }
        }

    def validate(self, attrs):
        # 比较openid
        print(attrs)
        access_token = attrs['access_token']
        openid = OAuthQQ.check_save_user_token(access_token)

        if openid is None:
            raise serializers.ValidationError("缺少access_token")
        attrs['openid'] = openid
        # 比较验证码
        mobile = attrs['mobile']
        redis_conn = create_redis_conn('sms_code')

        real_sms_code = redis_conn.get('sms_code_%s' % mobile)  # None
        print(real_sms_code)
        if real_sms_code is None:
            raise serializers.ValidationError('短信验证码已过期')
        sms_code = attrs['sms_code']
        if sms_code != real_sms_code.decode():
            raise serializers.ValidationError('短信验证码错误')
        try:
            user = User.objects.get(mobile=mobile)
        except User.DoesNotExist:
            user = None
        else:
            password = attrs['password']
            if not user.check_password(password):
                raise serializers.ValidationError('密码错误')
        attrs['user'] = user
        return attrs

    def create(self, validated_data):
        user = validated_data['user']
        # 产生随机用户名创建对象
        if user is None:
            username = base64.b64encode(os.urandom(9))
            password = validated_data['password']
            mobile = validated_data['mobile']
            user = User.objects.create_user(username=username, password=password, mobile=mobile)
        # 将QQ号与创建的对象关联
        # oauthqq_user = OAuthQQUser()
        # oauthqq_user.openid = validated_data['openid']
        # oauthqq_user.user = validated_data['user']
        # oauthqq_user.save()
        openid = validated_data['openid']
        OAuthQQUser.objects.create(
            user=user,
            # openid=validated_data['openid']
            openid=openid
        )
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        payload = jwt_payload_handler(user)
        token = jwt_encode_handler(payload)
        user.token = token
        return user
